package com.orhon.smartcampus.modules.notice.mutation;

import com.alibaba.fastjson.JSON;
import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.dao.SchoolsDao;
import com.orhon.smartcampus.modules.base.entity.Schools;
import com.orhon.smartcampus.modules.notice.InputMapper.NoticeInputMapper;
import com.orhon.smartcampus.modules.notice.dao.NoticeAndUserDao;
import com.orhon.smartcampus.modules.notice.dao.NoticeDao;
import com.orhon.smartcampus.modules.notice.entity.Notice;
import com.orhon.smartcampus.modules.notice.entity.NoticeAndSchool;
import com.orhon.smartcampus.modules.notice.gqlInputModel.GQLNoticeInput;
import com.orhon.smartcampus.modules.user.dao.TokenService;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class AddNoticeMutation implements DataFetcher {

    @Autowired
    NoticeDao noticeDao;

//    @Autowired
//    UsersDao usersDao;

    @Autowired
    SchoolsDao schoolsDao;

    @Autowired
    TokenService tokenService;

    @Autowired
    NoticeAndUserDao noticeAndUserDao;

    /**
     * 通知公告新增/修改接口
     * editor : ths
     */
    @Override
    public Object get(DataFetchingEnvironment environment) throws Exception {

        //String token = (String) SecurityUtils.getSubject().getPrincipal();
//        String token = tokenService.getSystemToken();
        //String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX3R5cGUiOiJhZG1pbiIsInNjaG9vbF9pZCI6MSwiZXhwIjoxNTc0NjMzMzUzLCJ1c2VyaWQiOjEsInVzZXJuYW1lIjoidGVhY2hlciJ9.YDTkSQK3DY5QV9yKJwg82I-Byc07ARnHXs5BK9_b-dA";
//        Long schoolId = JwtUtils.getSchoolId(token);
        GQLNoticeInput input = NoticeInputMapper.MAPPER.mapInput(environment.getArgument("inputData"));

        Notice notice = null;

        if (input.getId() != null) {
            notice = noticeDao.get(Notice.class, input.getId());
            notice.setUpdatedAt(new Date());
        } else {
            notice = new Notice();
            notice.setCreatedAt(new Date());
        }
        if (input.getSchool_id() != null) {
            notice.setBaseSchoolsBySchoolId(schoolsDao.get(Schools.class, input.getSchool_id()));
        }
        if(input.getNoticeTitle() != null){
            notice.setNoticeTitle(JSON.toJSONString(input.getNoticeTitle()));
        }
        if(input.getNoticeContent() != null){
            notice.setNoticeContent(JSON.toJSONString(input.getNoticeContent()));
        }
        if(input.getSendingTime() != null){
            notice.setSendingTime(input.getSendingTime());
        }
        // 接受人
        if(input.getSchools() != null){
            List<Schools> ttt=new ArrayList<>();
            input.getSchools().forEach(g -> {
                try {
                    Schools a = schoolsDao.findById(Long.valueOf(g));
                    ttt.add(a);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            notice.setSchools(ttt);
        }
        try{
            noticeDao.saveOrUpdate(notice);
            if(notice.getId().longValue()!=0){
                if(input.getSchools() != null){
                    List<Integer> usersIds = input.getSchools();//接受人
                    List<NoticeAndSchool> usrCount = noticeAndUserDao.usersList(notice.getId().longValue());//是否有接受人记录
                    for (NoticeAndSchool usr : usrCount) {
                        // teacherAndGradesDao.update(grades);//假删
                        noticeAndUserDao.deleteById(usr.getId());
                    }
                    //if(periodCount>0){
                    for(Integer uid:usersIds){
                        Long pid = uid.longValue();
                        NoticeAndSchool noticeAndUser=new NoticeAndSchool(notice.getId(),pid);
                        noticeAndUserDao.saveOrUpdate(noticeAndUser);//新数据
                    }

                }

                //session.save(teacherAndPeriods);
                //transaction.commit();

            }
        }
        catch (Exception e){
            return Result.error(500,""+e);
        }
        return Result.ok();
    }

    private String convertJavaBcryptPassword(String oldPass) {
        String old_password = oldPass;
        String new_password = "";
        if (old_password.charAt(2) == 'a') {
            StringBuilder strBuilder = new StringBuilder(old_password);
            strBuilder.setCharAt(2, 'y');
            new_password = strBuilder.toString();
            return new_password;
        } else {
            return old_password;
        }
    }
}
